<template>
  <CustomerLayout>
    <div class="checkout-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <el-button 
          link 
          @click="goBack" 
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
          {{ backButtonText }}
        </el-button>
        <h2>订单结算</h2>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" size="40"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <!-- 结算内容 -->
      <div v-else class="checkout-content">
        <!-- 配送地址 -->
        <div class="address-section">
          <div class="section-title">
            <el-icon><Location /></el-icon>
            配送地址
            <el-button 
              link 
              size="small" 
              @click="goToAddressManage"
              class="manage-address-btn"
            >
              管理地址
            </el-button>
          </div>
          
          <div v-if="selectedAddress" class="address-content" @click="chooseAddress">
            <div class="address-info">
              <div class="contact">
                <span class="name">{{ selectedAddress.name }}</span>
                <span class="phone">{{ selectedAddress.phone }}</span>
                <el-tag v-if="selectedAddress.isDefault" size="small" type="warning">默认</el-tag>
              </div>
              <div class="address">
                {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detail }}
              </div>
            </div>
            <el-icon class="address-arrow"><ArrowRight /></el-icon>
          </div>
          
          <div v-else class="no-address" @click="chooseAddress">
            <el-icon size="20"><Location /></el-icon>
            <span>请选择收货地址</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>

        <!-- 配送信息 -->
        <div class="delivery-section">
          <div class="section-title">
            <el-icon><Van /></el-icon>
            配送信息
          </div>
          <div class="delivery-info">
            <span>立即配送，预计 {{ storeInfo.deliveryTime || 35 }}分钟 送达</span>
            <span class="delivery-fee">配送费：¥{{ storeInfo.deliveryFee?.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 订单详情 -->
        <div class="order-section">
          <div class="section-title">
            <el-icon><Shop /></el-icon>
            订单详情 - {{ storeInfo.name }}
          </div>
          <div class="goods-list">
            <div v-for="item in selectedItems" :key="item.id" class="goods-item">
              <el-image 
                :src="item.foodImage" 
                :alt="item.foodName"
                fit="cover"
                class="goods-image"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="goods-info">
                <div class="goods-name">{{ item.foodName }}</div>
                <div v-if="item.attributes && item.attributes.length" class="goods-specs">
                  <span v-for="(attr, index) in item.attributes" :key="index">
                    {{ attr.name }}: {{ attr.options.join(', ') }}
                    <span v-if="index < item.attributes.length - 1">; </span>
                  </span>
                </div>
                <div class="goods-meta">
                  <span class="quantity">x{{ item.quantity }}</span>
                  <span class="price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 餐具份数和备注 -->
          <div class="order-options">
            <div class="option-item">
              <span class="option-label">
                <el-icon><Bowl /></el-icon>
                餐具份数
              </span>
              <el-select v-model="utensils" size="small" style="width: 80px">
                <el-option label="1份" :value="1" />
                <el-option label="2份" :value="2" />
                <el-option label="3份" :value="3" />
                <el-option label="4份" :value="4" />
                <el-option label="5份" :value="5" />
              </el-select>
            </div>
            <div class="option-item">
              <span class="option-label">
                <el-icon><EditPen /></el-icon>
                订单备注
              </span>
              <el-input 
                v-model="remark" 
                placeholder="请输入备注信息（选填）"
                type="textarea"
                :rows="2"
                maxlength="100"
                show-word-limit
                class="remark-input"
              />
            </div>
          </div>
        </div>

        <!-- 价格明细 -->
        <div class="price-section">
          <div class="section-title">
            <el-icon><Money /></el-icon>
            价格明细
          </div>
          <div class="price-details">
            <div class="price-item">
              <span>商品总价</span>
              <span>¥{{ goodsTotal.toFixed(2) }}</span>
            </div>
            <div class="price-item">
              <span>配送费</span>
              <span>¥{{ (storeInfo.deliveryFee || 0).toFixed(2) }}</span>
            </div>
            <div class="price-item total">
              <span>实付金额</span>
              <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部提交栏 -->
      <div v-if="!loading" class="submit-bar">
        <div class="total-info">
          <div class="delivery-time">立即配送 • 预计{{ storeInfo.deliveryTime || 35 }}分钟送达</div>
          <div class="total-amount">实付：¥{{ totalAmount.toFixed(2) }}</div>
        </div>
        <el-button 
          type="primary" 
          size="large"
          @click="submitOrder"
          :loading="submitting"
          :disabled="!selectedAddress"
          class="submit-btn"
        >
          {{ submitting ? '创建订单中...' : '提交订单' }}
        </el-button>
      </div>
    </div>

    <!-- 支付确认弹窗 -->
    <PaymentDialog
      v-model:visible="paymentVisible"
      :order-info="orderInfo"
      :store-name="storeInfo.name"
      :address-info="addressInfo"
      :paying="paying"
      @pay="processPayment"
      @cancel="cancelPayment"
    />

    <!-- 地址选择弹窗 -->
    <el-dialog
      v-model="addressVisible"
      title="选择收货地址"
      width="600px"
      class="address-dialog"
    >
      <div class="address-list">
        <div 
          v-for="address in addressList" 
          :key="address.id"
          :class="['address-item', { selected: selectedAddress?.id === address.id }]"
          @click="selectAddress(address)"
        >
          <div class="address-info">
            <div class="contact">
              <span class="name">{{ address.name }}</span>
              <span class="phone">{{ address.phone }}</span>
              <el-tag v-if="address.isDefault" size="small" type="warning">默认</el-tag>
            </div>
            <div class="address">
              {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
            </div>
          </div>
          <el-icon v-if="selectedAddress?.id === address.id" class="selected-icon" color="#409EFF">
            <Check />
          </el-icon>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="addressVisible = false">取消</el-button>
        <el-button type="primary" @click="goToAddAddress">新增地址</el-button>
      </template>
    </el-dialog>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ArrowLeft, 
  ArrowRight, 
  Location, 
  Van, 
  Shop, 
  Picture, 
  Bowl, 
  EditPen, 
  Money, 
  Loading,
  Check
} from '@element-plus/icons-vue';
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import PaymentDialog from "@/components/customer/PaymentDialog.vue";
import { orderApi, addressApi, cartApi, storeApi } from '@/api/customer';
import type { CartItem, Address, Store } from '@/types/customer';

const router = useRouter();
const route = useRoute();

// 响应式数据
const loading = ref(true);
const submitting = ref(false);
const paying = ref(false);
const paymentVisible = ref(false);
const addressVisible = ref(false);

const selectedItems = ref<CartItem[]>([]);
const selectedAddress = ref<Address | null>(null);
const addressList = ref<Address[]>([]);
const storeInfo = ref<Partial<Store>>({});
const orderInfo = ref<any>({});

const utensils = ref(1);
const remark = ref('');

// 计算属性
const goodsTotal = computed(() => {
  return selectedItems.value.reduce((total, item) => total + item.price * item.quantity, 0);
});

const totalAmount = computed(() => {
  return goodsTotal.value + (storeInfo.value.deliveryFee || 0);
});

const addressInfo = computed(() => {
  const addr = selectedAddress.value;
  if (!addr) return '';
  return `${addr.province}${addr.city}${addr.district}`;
});

// 返回按钮文字
const backButtonText = computed(() => {
  const storeId = route.query.storeId;
  return storeId ? '返回商家' : '返回购物车';
});

// 页面初始化
onMounted(() => {
  loadPageData();
});

// 加载页面数据
const loadPageData = async () => {
  try {
    loading.value = true;
    
    // 首先尝试加载购物车商品
    await loadSelectedCartItems();
    
    // 如果有商品，加载商家信息
    if (selectedItems.value.length > 0) {
      const storeId = selectedItems.value[0].storeId;
      await Promise.all([
        loadStoreInfo(storeId), // 加载商家信息
        loadAddresses()         // 加载地址列表
      ]);
    } else {
      // 没有商品时也要加载地址
      await loadAddresses();
    }
    
    console.log('页面数据加载完成');
    
  } catch (error: any) {
    console.error('加载页面数据失败:', error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 加载选中的购物车商品
const loadSelectedCartItems = async () => {
  try {
    // 从路由参数获取店铺ID或从本地存储获取
    const storeId = route.query.storeId ? parseInt(route.query.storeId as string, 10) : null;
    
    if (!storeId) {
      // 尝试从本地存储获取
      const cartData = JSON.parse(localStorage.getItem('checkoutData') || '{}');
      if (!cartData.storeId) {
        ElMessage.warning('请先选择要结算的商品');
        router.push('/customer/cart');
        return;
      }
      
      // 从本地存储恢复数据
      selectedItems.value = cartData.items || [];
      if (selectedItems.value.length > 0) {
        await loadStoreInfo(cartData.storeId);
      }
      return;
    }
    
    // 从API获取店铺购物车数据
    const response = await cartApi.getStoreCart(storeId);
    const cartData = response.data.data;
    
    if (!cartData || !cartData.items || cartData.items.length === 0) {
      ElMessage.warning('购物车为空，请先添加商品');
      router.push('/customer/cart');
      return;
    }
    
    // 处理购物车商品数据，确保字段名称正确
    selectedItems.value = cartData.items.map(item => ({
      id: item.id,
      foodId: item.foodId,
      foodName: item.foodName || item.name,
      foodImage: item.foodImage || item.image,
      price: item.price,
      quantity: item.quantity,
      storeId: storeId,
      attributes: item.attributes || []
    }));
    
    console.log('加载购物车商品成功:', selectedItems.value);
    
  } catch (error) {
    console.error('加载购物车商品失败:', error);
    ElMessage.error('加载购物车数据失败');
    throw error;
  }
};

// 加载地址列表
const loadAddresses = async () => {
  try {
    const response = await addressApi.getList();
    const addresses = response.data.data || [];
    
    // 处理地址数据，确保字段名称一致
    addressList.value = addresses.map(addr => ({
      id: addr.id,
      receiver: addr.receiver,
      phone: addr.phone,
      province: addr.province,
      city: addr.city,
      district: addr.district,
      detailAddress: addr.detailAddress,
      isDefault: addr.isDefault,
      // Vue组件中使用的字段名
      name: addr.receiver,
      detail: addr.detailAddress
    }));
    
    // 设置默认地址
    const defaultAddress = addressList.value.find(addr => addr.isDefault) || addressList.value[0];
    if (defaultAddress) {
      selectedAddress.value = defaultAddress;
      console.log('设置默认地址成功:', defaultAddress);
    } else {
      console.log('没有可用地址');
    }
    
  } catch (error) {
    console.error('加载地址失败:', error);
    ElMessage.error('加载地址失败');
  }
};

// 加载商家信息
const loadStoreInfo = async (storeId: number) => {
  try {
    const response = await storeApi.getStoreDetail(storeId.toString());
    const storeData = response.data.data || {};
    
    // 处理店铺数据，设置默认值
    storeInfo.value = {
      id: storeData.id,
      name: storeData.name || '未知店铺',
      logo: storeData.logo || '',
      deliveryTime: storeData.deliveryTime || 35,
      deliveryFee: storeData.deliveryFee || 0,
      ...storeData
    };
    
    console.log('加载店铺信息成功:', storeInfo.value);
    
  } catch (error) {
    console.error('加载商家信息失败:', error);
    ElMessage.error('加载商家信息失败');
  }
};

// 选择地址
const chooseAddress = () => {
  addressVisible.value = true;
};

// 选择地址
const selectAddress = (address: Address) => {
  selectedAddress.value = address;
  addressVisible.value = false;
};

// 返回购物车
const goBack = () => {
  // 如果有storeId参数，说明是从商家详情页面跳转过来的，返回商家详情页面
  const storeId = route.query.storeId;
  if (storeId) {
    router.push(`/customer/store/${storeId}`);
  } else {
    // 否则返回购物车页面
    router.push('/customer/cart');
  }
};

// 跳转地址管理
const goToAddressManage = () => {
  router.push('/customer/address');
};

// 新增地址
const goToAddAddress = () => {
  router.push('/customer/address/add');
  addressVisible.value = false;
};

// 提交订单
const submitOrder = async () => {
  // 更严格的表单验证
  if (!selectedAddress.value || !selectedAddress.value.id) {
    ElMessage.error('请选择收货地址');
    return;
  }
  
  if (!selectedItems.value || selectedItems.value.length === 0) {
    ElMessage.error('购物车为空，请先添加商品');
    return;
  }
  
  // 验证地址完整性
  const address = selectedAddress.value;
  if (!address.name || !address.phone || !address.province || !address.detail) {
    ElMessage.error('收货地址信息不完整，请重新选择');
    return;
  }
  
  // 验证storeId
  const storeId = selectedItems.value[0].storeId;
  if (!Number.isInteger(storeId) || storeId <= 0) {
    ElMessage.error('店铺信息错误');
    return;
  }
  
  console.log('[Debug] 开始创建订单');
  submitting.value = true;
  
  try {
    // 准备订单数据，确保参数格式正确
    const addressId = parseInt(address.id.toString(), 10);
    if (!Number.isInteger(addressId) || addressId <= 0) {
      throw new Error('地址ID无效');
    }
    
    const orderData = {
      storeId: storeId,
      addressId: addressId,
      remark: remark.value.trim() || ''
    };
    
    console.log('[Debug] 准备创建订单，数据:', orderData);
    
    // 创建订单
    const response = await orderApi.createOrder(orderData);
    console.log('[Debug] 创建订单返回数据:', response);
    
    // 检查返回数据
    if (!response.data || !response.data.data) {
      throw new Error('服务器返回数据为空');
    }
    
    const orderResult = response.data.data;
    const { id, orderNo, paymentAmount } = orderResult;
    
    if (!id) {
      throw new Error('订单ID为空');
    }
    if (!orderNo) {
      throw new Error('订单编号为空');
    }
    if (paymentAmount === undefined || paymentAmount === null) {
      throw new Error('支付金额为空');
    }
    
    // 保存订单信息
    orderInfo.value = {
      ...orderResult,
      id: id,
      orderNo: orderNo,
      paymentAmount: paymentAmount
    };
    
    console.log('[Debug] 订单创建成功，准备显示支付弹窗:', orderInfo.value);
    
    // 显示支付弹窗
    paymentVisible.value = true;
    
  } catch (error: any) {
    console.error('[Debug] 创建订单失败，完整错误:', error);
    ElMessage.error(error.message || '创建订单失败');
  } finally {
    submitting.value = false;
  }
};

// 处理支付
const processPayment = async () => {
  paying.value = true;
  
  try {
    console.log('[Debug] 开始支付，订单信息:', orderInfo.value);
    
    // 验证订单信息
    if (!orderInfo.value || !orderInfo.value.id) {
      throw new Error('订单信息错误');
    }
    
    // 调用支付接口，参照微信小程序的参数格式
    const orderIdNum = Number(orderInfo.value.id);
    const payResult = await orderApi.payOrder({
      orderId: orderIdNum,
      paymentType: 'WECHAT' 
    });
    
    console.log('[Debug] 支付接口返回:', payResult);
    
    if (!payResult || !payResult.data) {
      throw new Error('支付接口返回数据为空');
    }
    
    // 检查支付结果
    if (payResult.data.status === 200 || 
        (payResult.data.data && payResult.data.data.paymentStatus === 1)) {
      
      ElMessage.success('支付成功');
      
      // 关闭弹窗
      paymentVisible.value = false;
      
      // 清除本地存储的结算数据
      localStorage.removeItem('checkoutData');
      localStorage.removeItem('selectedCartItems');
      
      // 延迟跳转到订单详情页
      setTimeout(() => {
        router.push(`/customer/order/${orderInfo.value.id}`);
      }, 1500);
      
    } else {
      // 支付失败
      const errorMsg = payResult.data.data?.paymentMessage || 
                       payResult.data.message || 
                       '支付失败';
      throw new Error(errorMsg);
    }
    
  } catch (error: any) {
    console.error('[Debug] 支付失败:', error);
    ElMessage.error(error.message || '支付失败');
  } finally {
    paying.value = false;
  }
};

// 取消支付/订单
const cancelPayment = async () => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '确认取消', {
      confirmButtonText: '确定取消',
      cancelButtonText: '继续支付',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    });
    
    // 验证订单信息
    if (!orderInfo.value || !orderInfo.value.id) {
      throw new Error('订单信息错误');
    }
    
    console.log('[Debug] 开始取消订单:', orderInfo.value.id);
    
    // 取消订单
    await orderApi.cancelOrder(orderInfo.value.id);
    
    ElMessage.success('订单已取消');
    
    // 关闭弹窗，返回购物车
    paymentVisible.value = false;
    router.push('/customer/cart');
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('[Debug] 取消订单失败:', error);
      ElMessage.error(error.message || '取消订单失败');
    }
  }
};
</script>

<style scoped>
.checkout-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  padding-bottom: 120px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  margin-right: 15px;
  color: #666;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

/* 加载状态 */
.loading-container {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.loading-container p {
  margin-top: 15px;
}

/* 通用区块样式 */
.address-section,
.delivery-section,
.order-section,
.price-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #eee;
  font-weight: 600;
  color: #333;
  gap: 8px;
}

.manage-address-btn {
  margin-left: auto;
  color: #409EFF;
}

/* 地址区块 */
.address-content {
  display: flex;
  align-items: center;
  padding: 20px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.address-content:hover {
  background: #f8f9fa;
}

.address-info {
  flex: 1;
}

.contact {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.name {
  font-weight: 600;
  color: #333;
}

.phone {
  color: #666;
  font-size: 14px;
}

.address {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.address-arrow {
  color: #999;
}

.no-address {
  display: flex;
  align-items: center;
  padding: 20px;
  color: #999;
  cursor: pointer;
  transition: background-color 0.2s;
  gap: 10px;
}

.no-address:hover {
  background: #f8f9fa;
}

/* 配送信息 */
.delivery-info {
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.delivery-fee {
  color: #ff6600;
  font-weight: 600;
}

/* 商品列表 */
.goods-list {
  padding: 0 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  gap: 15px;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  color: #ccc;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.goods-specs {
  font-size: 12px;
  color: #999;
  margin-bottom: 6px;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity {
  color: #666;
  font-size: 14px;
}

.price {
  color: #ff6600;
  font-weight: 600;
}

/* 订单选项 */
.order-options {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

.option-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  gap: 15px;
}

.option-item:last-child {
  margin-bottom: 0;
}

.option-label {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
  white-space: nowrap;
  margin-top: 6px;
}

.remark-input {
  flex: 1;
}

/* 价格明细 */
.price-details {
  padding: 15px 20px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.price-item:last-child {
  margin-bottom: 0;
}

.price-item.total {
  padding-top: 10px;
  border-top: 1px solid #eee;
  font-size: 16px;
  font-weight: 600;
}

.total-price {
  color: #ff6600;
  font-size: 18px;
}

/* 底部提交栏 */
.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 15px 20px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.total-info {
  flex: 1;
  margin-right: 20px;
}

.delivery-time {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #ff6600;
}

.submit-btn {
  min-width: 120px;
  height: 44px;
}

/* 地址选择弹窗 */
.address-list {
  max-height: 400px;
  overflow-y: auto;
}

.address-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 6px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s;
}

.address-item:hover {
  border-color: #409EFF;
  background: #f0f8ff;
}

.address-item.selected {
  border-color: #409EFF;
  background: #f0f8ff;
}

.address-item:last-child {
  margin-bottom: 0;
}

.selected-icon {
  margin-left: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .checkout-container {
    padding: 15px;
  }
  
  .goods-item {
    gap: 10px;
  }
  
  .goods-image {
    width: 50px;
    height: 50px;
  }
  
  .option-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .submit-bar {
    flex-direction: column;
    padding: 15px;
    gap: 10px;
  }
  
  .total-info {
    margin-right: 0;
    text-align: center;
  }
  
  .submit-btn {
    width: 100%;
  }
  
  .payment-dialog {
    width: 90% !important;
  }
  
  .payment-actions {
    flex-direction: column;
  }
  
  .address-dialog {
    width: 90% !important;
  }
}
</style>
